import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_aygsh/util/SignUtil.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../base/Constant.dart';
import 'BankListPage.dart';
import '../../util/BlankToolBarTool.dart';
import '../../util/LoadingUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../event/CardEvent.dart';
import '../../base/application.dart';
import '../../entity/BankEntity.dart';

class AddCardPage extends StatefulWidget {
  AddCardPage({Key key}) : super(key: key);

  @override
  _AddCardPageState createState() => _AddCardPageState();
}

class _AddCardPageState extends State<AddCardPage> {
  final _nameController = TextEditingController(); //
  final _cardNumController = TextEditingController(); //
  BlankToolBarModel barModel = BlankToolBarModel();
  String token = "";
  String bank_id = "";
  String bank_name = '';

  @override
  void deactivate() {
    var bool = ModalRoute.of(context).isCurrent;

    if (bool) {
      print("页面即将显示");
    }
  }

  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
       setState(() {
         token = value;
       });
      
    });
   
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: new Text(
            "添加银行卡",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black),
          ),
          elevation: 0.5,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.black),
        ),
        body: BlankToolBarTool.blankToolBarWidget(
          context,
          model: barModel,
          body: Container(
            child: Column(
              children: <Widget>[
                Expanded(
                    child: new SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        physics: BouncingScrollPhysics(),
                        child: new Column(children: <Widget>[
                          Container(
                            padding: EdgeInsets.all(
                                ScreenUtil.getInstance().setHeight(DP_20)),
                            margin: EdgeInsets.fromLTRB(
                                0,
                                ScreenUtil.getInstance().setHeight(DP_20),
                                0,
                                0),
                            color: Colors.white,
                            child: new GestureDetector(
                              onTap: () {
                                Navigator.of(context).push<BankEntity>(
                                    new MaterialPageRoute(builder: (context) {
                                  return new BankPageLsit();
                                })).then((BankEntity data){
                                  setState(() {
                                    bank_name = data.bank_name;
                                    bank_id = data.bank_id;
                                  });
                                });
                              },
                              child: new Row(
                                children: <Widget>[
                                  Text('  '),
                                  Expanded(
                                    child: Text(
                                      '选择银行',
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(SMALL_FONT_SIZE),
                                          color: Colors.black87),
                                    ),
                                  ),
                                  Expanded(
                                    child: Text(
                                      bank_name==null?'':bank_name,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(SMALL_FONT_SIZE),
                                          color: Colors.black87),
                                    ),
                                  ),
                                  Icon(
                                    Icons.arrow_forward_ios,
                                    color: Colors.black87,
                                    size: 20,
                                  )
                                ],
                              ),
                            ),
                          ),
                          Divider(
                            height: 1,
                          ),
                          createInputText(_nameController,
                              hint: '',
                              text: '姓名',
                              type: TextInputType.text),
                          Divider(
                            height: 1,
                          ),
                          createInputText(_cardNumController,
                              hint: '',
                              text: '卡号',
                              type: TextInputType.phone),
                          new Container(
                            width: double.infinity,
                            height: ScreenUtil.getInstance().setHeight(DP_70),
                            margin: EdgeInsets.fromLTRB(50, 30, 50, 0),
                            decoration: new BoxDecoration(
                              color:mainColor,
                                borderRadius: BorderRadius.circular(20.0)),
                            padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                            child: new FlatButton(
                              child: new Padding(
                                padding: EdgeInsets.all(0.0),
                                child: new Text(
                                  '添加',
                                  style: new TextStyle(
                                      color: Colors.white, fontSize: 16),
                                ),
                              ),
                              onPressed: () {
                                submitFeed();
                              },
                            ),
                          )
                        ]))),
              ],
            ),
          ),
        ));
  }

  Widget createInputText(TextEditingController controller,
      {obscureText: false, String hint, String text, TextInputType type}) {
    FocusNode focusNode = barModel.getFocusNodeByController(controller);
    return Container(
        color: Colors.white,
        padding:
            new EdgeInsets.fromLTRB(kMargin20 * 2, kMargin20, kMargin20 * 2, 0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: new Text(
                      text,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
                    ),
                  ),
                  new Container(
                    width: ScreenUtil.getInstance().setWidth(750) * 0.6,
                    child: new TextField(
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText,
                        focusNode: focusNode),
                  ),
                  new IconButton(
                    icon: new Icon(Icons.clear, color: Colors.black45),
                    onPressed: () {
                      controller.clear();
                    },
                  ),
                ]),
            // Divider(
            //   height: 1,
            // ),
          ],
        ));
  }

  void submitFeed() {
    //提示
    String msgStr = "";

    if (!_cardNumController.text.isNotEmpty) {
      msgStr = "卡号不能为空";
    }
    if (!_nameController.text.isNotEmpty) {
      msgStr = "姓名不能为空";
    }
    if (bank_id == '' || bank_id == null) {
      msgStr = "请选择银行";
    }

    if (msgStr != '') {
      showDialog(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提示信息"),
              content: new Text(msgStr),
              actions: <Widget>[
                new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              ],
            );
          });
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: '添加中...',
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
      add();
    }
  }

  add() async {
    // //添加银行卡
    // FormData formData = new FormData.fromMap({
    //   "token": token,
    //   'bank_id': bank_id,
    //   'account': _cardNumController.text,
    //   'account_name': _nameController.text,
    //   // 'is_beneficiary': 'Y'
    // });
     Map map = new Map();
    map['token'] = token;
     map['bank_id'] = bank_id;
       map['account'] = _cardNumController.text;
       map['truename'] = _nameController.text;
    map['sign_type'] = createSignType(Api.URL_BANKCARD_ADD);

    // print(formData);
    Response<String> response =
        await HttpUtil().post(Api.URL_BANKCARD_ADD, data: getSign(map));
    Map userMap = json.decode(response.data);
    print('---添加');
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1) {
      APPLIC.eventBus.fire(CardEvent());
      Navigator.of(context).pop("1");
    }
    return true;
  }
}
